<template>
  <div class="detail">
    <div class="head">
      <p @click="back"><i class="el-icon-back"></i></p>
      <p>{{compData.data.title}}</p>
      <p>{{compData.data.author}} <el-tag class="focus">关注</el-tag> </p>
    </div>
    <hr>
    <div v-html="compData.data.content" class="content"></div>
    <ul v-if="comment.data.length > 0">
      <li v-for="item in comment.data" :key="item._id">{{item.username}} 评论了:{{ item.content }}</li>
    </ul>
    <p v-else>暂无评论！ </p>
    <hr>
    文章评论：<br/><el-input type="textarea" v-model="articleCommentContent"></el-input><br/><br/><br/>
    <el-button type="primary" @click="submitComment">确定</el-button>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from '@vue/runtime-core';
import { ElMessage } from 'element-plus';
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex';
import { http } from '../../utils/http';
const store = useStore()
const route = useRoute()
const router = useRouter()
let compData = reactive({data:{}})
onMounted(async () => {
  let res = await http.get(`/article/findOne?id=${route.query.id}`)
  compData.data = res.data
  comment.data = res.commentList
  console.log(res);
})

// 回退
const back = () => {
  router.go(-1)
}

// 评论列表
let comment = reactive({data: []})
// 评论
const articleCommentContent = ref('')
const submitComment = async () => {
  let articleId = compData.data.id
  let author = compData.data.author
  let articleTitle = compData.data.title
  let username = store.state.msg.username
  let content = articleCommentContent.value
  let date = new Date()
  let createTime = date.getTime()
  // console.log({articleId, author, articleTitle, username, content, createTime});
  let res = await http.post('/comment/add', {articleId, author, articleTitle, username, content, createTime})
  if(res.code === 200){
    ElMessage.success({
      type: 'success',
      message: '评论成功！'
    })
    comment.data.push({articleId, author, articleTitle, username, content, createTime})
  }else{
    ElMessage.error({
      type: 'error',
      message: '评论失败！'
    })
  }
}
</script>

<style lang="scss" scoped>
.head{
  display: flex;
  justify-content: space-between;
  font-size: 28px;
  p:nth-child(1){
    cursor: pointer;
  }
  p:nth-child(2){
    font-weight: 700;
  }
}
.detail{
  div{
    width: 80%;
    margin: 20px auto 0;
  }
}
.content{
  border: 1px solid #ccc;
  height: 500px;
  overflow: auto;
}
.focus{
  cursor: pointer;
}
</style>